package com.fj.springdataldap.web;

import com.fj.springdataldap.domain.Account;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.query.LdapQueryBuilder;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.naming.InvalidNameException;
import java.util.List;


/**
 * @author fj
 * @date 2024/3/21 10:44
 */
@RestController
public class UserController {

    @Resource
    private LdapTemplate ldapTemplate;

    @GetMapping(value = "test")
    public String test() throws InvalidNameException {
        //ou=People,dc=fj,dc=com
//        return ldapTemplate.list("uid=admin,ou=People,dc=fj,dc=com");
        // 查询 所有用户，注意 person类查询条件
        List<Account> ps = ldapTemplate.findAll(Account.class);
        System.out.println(ps);
//        LdapQueryBuilder.query().base(new LdapName("admin"));
        List<Account> accounts = ldapTemplate.find(LdapQueryBuilder.query().attributes("userid","ou").filter(new EqualsFilter("uid","ldapuser1")), Account.class);
        System.out.println(accounts);
        ldapTemplate.authenticate(LdapQueryBuilder.query().filter(new EqualsFilter("uid","ldapuser1")),"123456");
        boolean authenticate = ldapTemplate.authenticate("ou=People", "uid=ldapuser1", "123456");
        System.out.printf("认证成功:%s",authenticate);
        return "ok";
    }

    @GetMapping(value = "login")
    public boolean login(@RequestParam(required = false) String username, @RequestParam(required = false) String password) {
        try{
            Assert.notNull(username,"用户名不能为空");
            Assert.notNull(password,"密码不能为空");
            boolean authenticate = ldapTemplate.authenticate("ou=People", String.format("uid=%s",username), password);
            System.out.printf("\n认证成功:%s",authenticate);
            return authenticate;
        }catch (IllegalArgumentException e){
            System.out.println(e.getMessage());
        }
        return false;
    }
}
